from django.contrib import admin
from django import forms
from . import models
from django.dispatch import receiver
from django.db.models.signals import post_delete
from django.conf import settings
import os
# Register your models here.

class DocumentModelForm(forms.ModelForm):



    class Meta:
        model = models.DocumentModel
        fields = [ 'orderId','detail','date',  'company','amount','tax','type','document_type', 'state','remarks','report_file',]  # 或者指定需要的字段


@admin.register(models.DocumentModel)
class DocumentModelAdmin(admin.ModelAdmin):
    form = DocumentModelForm
    list_display = ('orderId','detail','date','report_name', 'company','amount','tax', 'type','document_type', 'state','remarks','report_file')
    search_fields = ('report_name',)
    # list_filter = ('report_name',)



# 定义信号接收器：在模型实例被删除后触发
@receiver(post_delete, sender=models.DocumentModel)
def delete_document_file(sender, instance,** kwargs):
    """删除模型记录时，同时删除对应的附件文件"""
    if instance.report_file:
        file_path = os.path.join(settings.MEDIA_ROOT, str(instance.report_file))
        if os.path.exists(file_path):
            os.remove(file_path)



class KnowledgeFileForm(forms.ModelForm):
    class Meta:
        model = models.KnowledgeFileModel
        fields = ( 'knowledge','file')
class KnowledgeFileInline(admin.TabularInline):
    model = models.KnowledgeFileModel
    form = KnowledgeFileForm  # 应用自定义表单

    classes = ['collapse'] # 添加collapse类，这是Django Admin内置的
    extra = 1  # 默认显示1行空明细，可动态添加
    verbose_name = "附件"
    verbose_name_plural = "附件"

    # 明细表单字段配置
    fields = ('file',)


    # readonly_fields = ('raw_name',)  # 创建时间只读

    # 2. 允许删除明细（默认 True，若之前手动设为 False 需改回）
    can_delete = True  # 显式启用删除功能（可选，默认 True，防止被意外禁用）
    # 优化外键选择体验（支持搜索）
    autocomplete_fields = ()  # 依赖base.RawModel的Admin配置了search_fields


@admin.register(models.KnowledgeModel)
class KnowledgeModelAdmin(admin.ModelAdmin):
    list_display = ('name',)
    fields = ('name', 'content')  # 确保 content 字段显示在编辑页
    # 在入库单编辑页嵌入明细项（核心配置）
    inlines = [KnowledgeFileInline,]
    # 关键：将不可编辑的字段设为只读
    readonly_fields = ('create_at', 'update_at')  # 加入这行
    # 表单字段分组
    # fieldsets = (
    #     ('研发内容', {
    #         'fields': ('name', 'content' ),
    #         'description': '请输入研发标题'
    #     }),
    #
    #     ('系统记录', {
    #         'fields': ('create_at', 'update_at'),
    #         'classes': ('collapse',),  # 可折叠
    #         'description': '创建和更新时间由系统自动记录，不可修改'
    #     })
    # )